package ar.edu.utn.frgp.banco.filtros;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUtils;

import ar.edu.utn.frgp.banco.domain.Cliente;

/**
 * Servlet Filter implementation class LogInFilter
 */
public class LogInFilter implements Filter {

	
    /**
     * Default constructor. 
     */
    public LogInFilter() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here
		
		HttpServletRequest req = ((HttpServletRequest) request);
		boolean cont = true;
		boolean excluida = false;
		@SuppressWarnings("deprecation")
		String url = HttpUtils.getRequestURL(req).toString().toLowerCase();
		
		String[] exclusionFolders = {req.getContextPath() + "/exc/",req.getContextPath() + "/static/"};
		
		for (String exc : exclusionFolders){
			if (url.contains(exc.toLowerCase())) excluida = true;
		}
		
		
		if (!excluida){
			System.out.println(url);
			HttpSession sesion = req.getSession(false);
			if (sesion != null){
				Cliente c = (Cliente) req.getSession().getAttribute("cliente");
				if (c == null || !c.isLogOk()){
					cont = false;
					req.setAttribute("errores", "Debe iniciar sesion");
					
					((HttpServletResponse)response).sendRedirect(req.getContextPath() +"/exc/login.jsp");
				}
			} else {
				cont = false;
				req.setAttribute("errores", "Debe iniciar sesion");
				((HttpServletResponse)response).sendRedirect(req.getContextPath() +"/exc/login.jsp");
			}
		}

		
		// pass the request along the filter chain
		if (cont){
			System.out.println(url);
			System.out.println(excluida);
			chain.doFilter(request, response);
		}
		
	}

	/**
	 * @see Filter#init(FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		
	}

}
